package com.example.javabasic.sample;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.google.common.base.Supplier;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author cph
 * @Date 2020/3/25
 */
public class SimpleTest {

    public static void main(String[] args) throws Exception {
        testBigDecimal();
    }

    private static void testBigDecimal() {
        BigDecimal cost = new BigDecimal("96455.83");
        BigDecimal flowRate = new BigDecimal(0.02).setScale(4, BigDecimal.ROUND_HALF_UP);
        BigDecimal serviceRate = new BigDecimal(0.02).setScale(4, BigDecimal.ROUND_HALF_UP);
        BigDecimal frameRate = new BigDecimal(0.033).setScale(4, BigDecimal.ROUND_HALF_UP);
        BigDecimal finalRate =
                BigDecimal.ONE
                        .divide(
                                BigDecimal.ONE
                                        .add(flowRate)
                                        .multiply(BigDecimal.ONE.add(frameRate)),
                                10,
                                BigDecimal.ROUND_HALF_UP)
                        .add(serviceRate);
        System.out.println(finalRate);
        System.out.println(cost.multiply(finalRate).setScale(4, BigDecimal.ROUND_HALF_UP));
    }

    public static List<Date> getListOfDaysBeforeNow(Date start, Date end) {
        List<Date> dateList = new ArrayList<>();
        Calendar fromCal = Calendar.getInstance();
        fromCal.setTime(start);
        Calendar toCal = Calendar.getInstance();
        Date now = new Date();
        if (end.after(now)) {
            end = now;
        }
        toCal.setTime(end);
        while (!fromCal.after(toCal)) {
            dateList.add(fromCal.getTime());
            fromCal.add(Calendar.DATE, 1);
        }
        return dateList;
    }


    private static void resolveJson() {
        String str = "{\n" +
                "    \"message\": \"OK\",\n" +
                "    \"code\": 0,\n" +
                "    \"data\": {\n" +
                "        \"page_info\": {\n" +
                "            \"total_number\": 1,\n" +
                "            \"page\": 1,\n" +
                "            \"page_size\": 10,\n" +
                "            \"total_page\": 1\n" +
                "        },\n" +
                "        \"list\": [\n" +
                "            {\n" +
                "                \"status\": \"CREATIVE_STATUS_AD_DISABLE\",\n" +
                "                \"creative_word_ids\": [],\n" +
                "                \"video_id\": \"v0d033g10000c702obrc77u401f8ila0\",\n" +
                "                \"ad_id\": 1719647613312123,\n" +
                "                \"creative_create_time\": \"2021-12-20 16:05:51\",\n" +
                "                \"title\": \"本地注意，如何买对保险？这款百万医疗险保障多！不花冤枉钱！\",\n" +
                "                \"creative_modify_time\": \"2021-12-20 16:06:22\",\n" +
                "                \"creative_id\": 1719651581961267,\n" +
                "                \"audit_reject_reason\": null,\n" +
                "                \"advertiser_id\": 1714830170929159,\n" +
                "                \"image_id\": \"tos-cn-p-0051/c4f492013add462195c861d33312f96b\",\n" +
                "                \"metarials\": [],\n" +
                "                \"third_party_id\": null,\n" +
                "                \"image_mode\": \"CREATIVE_IMAGE_MODE_VIDEO_VERTICAL\",\n" +
                "                \"image_ids\": null,\n" +
                "                \"bidword_list\": null,\n" +
                "                \"opt_status\": \"CREATIVE_STATUS_ENABLE\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    \"request_id\": \"2022020917433101021010501209710FAD\"\n" +
                "}";
        JSONObject jsonObject = JSON.parseObject(str);
        int code = (int) jsonObject.get("code");
        Map dataMap = (Map) jsonObject.get("data");
        String item = JSONArray.parseArray(dataMap.get("list").toString()).get(0).toString();
        JSONObject jsonObj = JSON.parseObject(item);
        String videoId = jsonObj.get("video_id").toString();
        Long creativeId = (Long) jsonObj.get("creative_id");
    }

    private static void supplierTest() {
        Supplier<Integer> a = () -> 10 + 1;
        Map map = new HashMap();
        map.put("a", a);
        int b = ((Supplier<Integer>) map.get("a")).get() + 1;
        System.out.println(b);
    }

    private static void replaceJsonString() {
        Map<String, String> option = new HashMap();

        Map rule = new HashMap();
        Map struct = new HashMap();
        struct.put("event_type", "$event_type");
        struct.put("event_time", "$event_time");
        struct.put("callback", "$callback");
        rule.put("struct", struct);
        rule.put("params", "event_type$normal,event_time$normal,callback$url");

        String[] array = rule.get("params").toString().split(",");
        for (String str : array) {
            String[] arr = str.split("\\$");
            if (arr[1].equals("normal")) {
                option.put(arr[0], "1");
            } else if (arr[1].equals("url")) {
                option.put(arr[0], "0");
            }
        }

        // {"event_type":"#event_type","callback":"#callback","event_time":"#event_time"}
        String structStr = JSON.toJSONString(rule.get("struct"));
        for (Map.Entry entry : option.entrySet()) {
            if (structStr.contains("$" + entry.getKey().toString())) {
                structStr = structStr.replace("$" + entry.getKey().toString(), entry.getValue().toString());
            }
        }

        JSONObject jsonObject = JSONObject.parseObject(structStr);
        System.out.println(jsonObject);
    }


    private static void interfaceDataConvert() {
        //        String s = "{\"Timestamp\":1636443484,\"EventType\":\"insert\",\"Rows\":[{\"generalize_id\":\"ztpztuiayb02\",\"id\":\"53502788\",\"tuiguang_id\":\"ztpztuia\",\"update_time\":\"2021-11-09 15:38:04\",\"url\":\"https://exchange.ybaobx.com/gift/detail?insuranceId=201202163156780IB237865\\\\u0026version=23\\\\u0026tuiguangId=ztpztuiayb02\\\\u0026channel=tgzxtopzdj_ta_dj_102_cver\\\\u0026brandName=OPPO\\\\u0026a_slotId=392930\\\\u0026a_cid=29123843079\\\\u0026a_tuiaId=taw-4791966117810007\\\\u0026a_deviceId=29cc5dba-a3af-4e34-b924-d4e51b6596e3\\\\u0026a_appId=83142\\\\u0026userId=null\\\\u0026a_oId=taw-4791966117810007\\\\u0026flowId=cfcd208495d565ef66e7dff9f98764da\\\\u0026flowTagId=cfcd208495d565ef66e7dff9f98764da\",\"user_id\":\"211109153804336CA450790\"}],\"Query\":\"\",\"SchemaName\":\"data_service\",\"TableName\":\"yb_media_user_login_promotion_channel\",\"BinlogFileNum\":1446,\"BinlogPosition\":376092458,\"Gtid\":\"\",\"Pri\":[\"id\"],\"EventID\":2995695,\"ColumnMapping\":{\"generalize_id\":\"Nullable(varchar(200))\",\"id\":\"int64\",\"tuiguang_id\":\"varchar(100)\",\"update_time\":\"timestamp\",\"url\":\"varchar(4000)\",\"user_id\":\"varchar(100)\"}}";
        String s = "{\"Timestamp\":1636443473,\"EventType\":\"update\",\"Rows\":[{\"generalize_id\":\"dllffz01\",\"id\":\"53502785\",\"tuiguang_id\":\"dllffz01\",\"update_time\":\"2021-11-09 15:37:31\",\"url\":\"https://exchange.ybaobx.com/gift/detail?insuranceId=201202163156780IB237865\\\\u0026userId=211109153725603CA828938\\\\u0026isWeChatMiniApp=1\\\\u0026userToken=80bfade2-92bc-4438-a418-50e381f5b248\\\\u0026appId=wxc01666feb3c14fcb\\\\u0026unionId=od4Me57CpY6F-rMWuX_vs692V8FY\\\\u0026openId=o-6TJ5Qo-8vYjAeF_jqMha83bb0c\\\\u0026version=30\\\\u0026tuiguangId=dllffz01\\\\u0026channel=tgzx_dll_ff_01_cver\\\\u0026distinctID=1636443444940-3526920-0999b0131a7a588-33347299\\\\u0026dailalaToken=05132F6B1EE441E0B1FFBD5E0154EB16\",\"user_id\":\"211109153725603CA828938\"},{\"generalize_id\":\"dllffz01\",\"id\":\"53502785\",\"tuiguang_id\":\"dllffz01\",\"update_time\":\"2021-11-09 15:37:54\",\"url\":\"https://exchange.ybaobx.com/gift/detail?insuranceId=201202163156780IB237865\\\\u0026userId=211109153725603CA828938\\\\u0026isWeChatMiniApp=1\\\\u0026userToken=80bfade2-92bc-4438-a418-50e381f5b248\\\\u0026appId=wxc01666feb3c14fcb\\\\u0026unionId=od4Me57CpY6F-rMWuX_vs692V8FY\\\\u0026openId=o-6TJ5Qo-8vYjAeF_jqMha83bb0c\\\\u0026version=30\\\\u0026tuiguangId=dllffz01\\\\u0026channel=tgzx_dll_ff_01_cver\\\\u0026distinctID=1636443444940-3526920-0999b0131a7a588-33347299\\\\u0026dailalaToken=05132F6B1EE441E0B1FFBD5E0154EB16\",\"user_id\":\"211109153725603CA828938\"}],\"Query\":\"\",\"SchemaName\":\"data_service\",\"TableName\":\"yb_media_user_login_promotion_channel\",\"BinlogFileNum\":1446,\"BinlogPosition\":376085725,\"Gtid\":\"\",\"Pri\":[\"id\"],\"EventID\":2995660,\"ColumnMapping\":{\"generalize_id\":\"Nullable(varchar(200))\",\"id\":\"int64\",\"tuiguang_id\":\"varchar(100)\",\"update_time\":\"timestamp\",\"url\":\"varchar(4000)\",\"user_id\":\"varchar(100)\"}}";
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray rows = (JSONArray) jsonObject.get("Rows");
        JSONObject obj = (JSONObject) rows.get(rows.size() - 1);
        String id = obj.get("id").toString();
        String user_id = obj.get("user_id").toString();
        String tuiguangId = obj.get("tuiguang_id").toString();
        String generalizeId = obj.get("generalize_id").toString();
        String url = obj.get("url").toString();
        Timestamp timestamp = Timestamp.valueOf(obj.get("update_time").toString());
        System.out.println(obj);
    }

    private static void splitTest1() {
        String str = "jtzx_ybks_yh_sj10011_cver|aer";
//        String[] split = str.split("\\|");
        String[] split = StringUtils.split(str, "|");
        String[] channelCodeArray = StringUtils.split(split[0], "_");
//        String[] channelCodeArray = split[0].split("_");
        String modelCode = channelCodeArray[0];
        System.out.println(modelCode);
    }

    private static void SpringStringUtils() {
        String s1 = "";
        String s2 = " ";
        String s3 = null;
        System.out.println("hasText: " + StringUtils.hasText(s1));
        System.out.println("hasText: " + StringUtils.hasText(s2));
        System.out.println("hasText: " + StringUtils.hasText(s3));
        System.out.println("hasLength: " + StringUtils.hasLength(s1));
        System.out.println("hasLength: " + StringUtils.hasLength(s2));
        System.out.println("hasLength: " + StringUtils.hasLength(s3));
    }

    public static String reverse(String originStr) {
        if (originStr == null || originStr.length() <= 1) {
            return originStr;
        }
        return reverse(originStr.substring(1)) + originStr.charAt(0);
    }


    private static void internTest() {
        String s1 = new StringBuilder("go").append("od").toString();
        System.out.println(s1.intern() == s1);

        String s2 = new StringBuilder("ja").append("va").toString();
        System.out.println(s2.intern() == s2);

        String s3 = new StringBuilder("wor").append("ld").toString();
        System.out.println(s3.intern() == s3);

        String s4 = new StringBuilder("go").append("to").toString();
        System.out.println(s4.intern() == s4);
    }

    private static void regularExpression() {
        String str = "${GATEWAY_APP_ID:57f14042}";
        String regEX = "\\$\\{(\\w+):(\\S+)\\}";
        Pattern pattern = Pattern.compile(regEX);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
        }
    }

    private static void clazzTypeTest() {
        Map<String, Object> map = new HashMap<>();
        // true
        System.out.println(map instanceof Map);
        // false
        System.out.println(map.getClass().equals(Map.class));
        // false
        System.out.println(map.getClass().getName().equals(Map.class.getName()));

        List<Map<String, Object>> list = new ArrayList<>();
        // true
        System.out.println(list instanceof List);
        // false
        System.out.println(list.getClass().equals(List.class));
    }

    private static void splitTest() {
        String string = "2020-08-18 22:39:07,2020-08-18 22:39:08";
        System.out.println(string.split(",")[0].trim());
        System.out.println(string.split(",")[1].trim());
    }

    private static void caseFormatTest() {
        // 连字符 转 小驼峰 "test-data" -> "testData"
        System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "test-data"));
        // 下划线 转 小驼峰 "test_data" -> "testData"
        System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "test_data"));
        // 下划线 转 大驼峰 "test_data" -> "TestData"
        System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "test_data"));

        // 小驼峰 转 下划线 test_data
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "testData"));
        // 大驼峰 转 下划线 test_data
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "TestData"));
        // 小驼峰 转 连字符 test-data
        System.out.println(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "testData"));
    }

    private static void regExIP() {
        String ip = "127.0.0.1,192.168.3.4,172.16.95.48,10.19.49.124";
        String regEx = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(ip);
        while (matcher.find()) {
            String result = matcher.group();
            System.out.println(result);
            break;
        }
    }

    private static void testJoin() {
        String s = String.join("--", "java", "is", "magic").concat("!!");
        System.out.println(s);
    }

    private static void testReg() {
        String str1 = "2019-01-01 00:00:00";
        String str2 = "2020-01-01 00:00:00";
        String str3 = "2021-01-01 00:00:00";
        System.out.println(str1.replaceAll("\\:|00|\\.0| ", "").replace("-", ""));
        System.out.println(str2.replaceAll("\\:|00|\\.0| ", "").replace("-", ""));
        System.out.println(str3.replaceAll("\\:|00|\\.0| ", "").replace("-", ""));
    }

    private static void testIntegerRange() {
        Integer i1 = -128;
        Integer i2 = 100;
        Integer i3 = 127;

        Integer i4 = 128;
        Integer i5 = -129;

        Integer integer1 = -128;
        Integer integer2 = 100;
        Integer integer3 = 127;

        Integer integer4 = 128;
        Integer integer5 = -129;

        // true
        System.out.println(i1 == integer1);
        // true
        System.out.println(i1.equals(integer1));
        // true
        System.out.println(i2 == integer2);
        // true
        System.out.println(i2.equals(integer2));
        // true
        System.out.println(i3 == integer3);
        // true
        System.out.println(i3.equals(integer3));
        // fasle
        System.out.println(i4 == integer4);
        // true
        System.out.println(i4.equals(integer4));
        // false
        System.out.println(i5 == integer5);
        // true
        System.out.println(i5.equals(integer5));
    }

    private static void streamTest() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        list.stream()
                .filter(item -> item > 3)
                .forEach(System.out::println);
    }

    private static void structureTest() {
        List<Map<String, List<String>>> result = new ArrayList<>();
        List<String> list1 = Arrays.asList("1", "22", "33");
        Map map1 = new HashMap();
        map1.put("menu", list1);
        result.add(map1);
        System.out.println(result);
    }

    private static void String2Integer() {
        String s = "1";
//        Integer integer = Integer.parseInt(s, Integer.MAX_VALUE);
        Integer integer = Integer.parseInt(s);
        System.out.println(integer);
    }

    private static void substringtest() {
        String str = "basic-mqMessages-query";
        //返回起始位置，下标从0开始
        int begin = str.indexOf("-");
        int end = str.lastIndexOf("-");
        String result = str.substring(begin + 1, end);
        System.out.println(result);
    }

    private static void replaceTest() {
        Map map = new HashMap<>();
        map.put("mobile", "[123456789]");
        String str = map.get("mobile").toString().replace("[", "").replace("]", "");
        System.out.println(str);
    }

}
